<template>
  <f7-page name="playerInfo" color-theme="red" @page:afterin="pageAfterin">
    <div
      ref="bg"
      class="bg_blur"
      :class="getThemeDark ? 'dark_bg' : 'light_bg'"
    ></div>
    <div style="position:absolute;left:0px;right:0px">
      <div class="navbarInfo">
        <div class="navbar_l" @click="$f7router.back()">
          <f7-button>
            <svg-icon iconClass="horn_down_white" />
          </f7-button>
        </div>
        <div class="navbar_m">
          <div class="mText" :class="{ textScroll: nowSong.name.length > 12 }">
            <span class="scrollSong" :data-text="nowSong.name + ' '">{{
              nowSong.name
            }}</span>
          </div>
          <div class="mText2">
            <span class="scrollSinger" :data-text="'-' + nowSong.singer"
              >-{{ nowSong.singer }}</span
            >
          </div>
        </div>
        <div class="navbar_r"></div>
      </div>
      <div class="volume_box">
        <svg-icon iconClass="sound_white" v-if="getVolume != 0" />
        <svg-icon iconClass="mute_white" v-else />
        <f7-range
          :min="0"
          :max="10"
          :step="1"
          :value="getVolume"
          color="white"
          class="progress"
          @range:changed="onVolumeChange"
        ></f7-range>
      </div>
      <div class="lyc_box" @click="showOrhiddenLyc()">
        <transition name="fade">
          <ul id="lyc" v-show="lycShow">
            <li
              class="lycItem"
              v-for="(item, index) in getLyricsArr"
              :key="index"
            >
              {{ item[1] }}
            </li>
            <li
              class="lycItem"
              v-if="!getLyricsArr.length && getMusicPlace != -1"
            >
              暂无歌词
            </li>
          </ul>
        </transition>
      </div>
      <div class="button_bar">
        <div class="button_bar_left">
          <f7-button @click.stop="changeFav(nowSong)">
            <svg-icon iconClass="is_favorite" v-if="nowSong.isFavorite" />
            <svg-icon
              iconClass="no_favorite_white"
              v-else-if="!nowSong.isFavorite && getThemeDark"
            />
            <svg-icon
              iconClass="no_favorite_white"
              v-else-if="!nowSong.isFavorite && !getThemeDark"
            />
          </f7-button>
          <f7-button @click.stop="goToUpdateLyc(nowSong)" v-if="getManageState">
            <svg-icon iconClass="upload_lyc_white" v-if="getThemeDark" />
            <svg-icon iconClass="upload_lyc_white" v-else-if="!getThemeDark" />
          </f7-button>
        </div>
        <div class="button_bar_right">
          <f7-button @click.stop="goToShare()">
            <svg-icon iconClass="share_white" v-if="getThemeDark" />
            <svg-icon iconClass="share_white" v-else-if="!getThemeDark" />
          </f7-button>
        </div>
      </div>
      <div class="progress_box">
        <span style="margin-right:0.1rem;color:#ffffff"
          >{{ currentTime | date }}
        </span>
        <f7-range
          :min="0"
          :max="100"
          :step="1"
          :value="moveValue"
          :label="true"
          color="red"
          class="progress"
          @range:changed="onPriceChange"
          ref="processRef"
          id="processId"
        ></f7-range>
        <span style="margin-left:0.1rem;color:#ffffff">{{
          duration | date
        }}</span>
      </div>
      <div class="playBtn_box">
        <f7-button class="f7-button" @click.stop="prevMusic">
          <svg-icon
            iconClass="next_song_white"
            class="lastSvg"
            style="transform:rotate(180deg)"
          />
        </f7-button>
        <f7-button class="f7-button playButton" @click.stop="play">
          <svg-icon :icon-class="playBtnClass + '_white'" class="playSvg" />
        </f7-button>
        <f7-button class="f7-button" @click.stop="nextMusic">
          <svg-icon iconClass="next_song_white" class="nextSvg" />
        </f7-button>
        <f7-button class="f7-button songList" @click.stop="openListState">
          <svg-icon iconClass="list_icon_white" class="listSvg" />
        </f7-button>
      </div>
    </div>
  </f7-page>
</template>
<script>
import { mapActions, mapGetters } from 'vuex'
import Vue from 'vue'
import { getElementOption, scrollSmoothly } from '@/utils/index.js'
import {
  addToMyFavorite,
  delFromMyFavorite,
  getSingerPosterUrl,
} from '@/api/index.js'
//使用jquery来实现歌词的平滑滚动，我太菜了，不会自己写
import jquery from 'jquery'
Vue.filter('date', function(input) {
  let time = new Date()
  time.setTime(input * 1000)
  let seconds =
    time.getSeconds() < 10 ? '0' + time.getSeconds() : time.getSeconds()
  return time.getMinutes() + '.' + seconds
})
export default {
  watch: {
    nowSong: {
      handler(newVal) {
        console.log('nowSong is changed!', newVal)
        let loading_flag = true
        let img_tim = new Image()
        img_tim.src = '/static/playerInfo_loading.png'
        img_tim.onload = () => {
          if (loading_flag) {
            this.$refs.bg.style.backgroundImage = `url('${img_tim.src}')`
          }
        }

        this.$store.dispatch('setLyrics', newVal).then(() => {
          let lyricContainer = document.getElementById('lyc')
          lyricContainer.scrollTop = 0
        })
        if (newVal) {
          //歌手海报背景图
          if (
            this.getSingerPoster.singer != this.nowSong.singer ||
            this.getSingerPoster.singer === ''
          ) {
            getSingerPosterUrl({ name: this.nowSong.singer })
              .then((res) => {
                if (res.code === 200) {
                  this.sendSingerPoster({
                    singer: this.nowSong.singer,
                    url: res.data.posterUrl,
                  })
                } else {
                  let timUrl
                  if (this.getThemeDark) {
                    timUrl = '/static/playerInfo_bg6.jpg'
                  } else {
                    timUrl = '/static/playerInfo_bg2.jpg'
                  }
                  this.sendSingerPoster({
                    singer: '',
                    url: timUrl,
                  })
                }
                let imgg = new Image()
                imgg.src = this.getSingerPoster.url
                imgg.onload = () => {
                  loading_flag = false
                  this.$refs.bg.style.backgroundImage = `url('${imgg.src}')`
                }
              })
              .catch((err) => {
                console.log(err)
              })
          } else {
            let imgg = new Image()
            imgg.src = this.getSingerPoster.url
            imgg.onload = () => {
              loading_flag = false
              this.$refs.bg.style.backgroundImage = `url('${imgg.src}')`
            }
          }
        }
        jquery('#lyc').scrollTop(0)

        // this.setLyricsArr();
      },
      // immediate:true,
      deep: true,
    },
    currentTime(newVal) {
      //处理歌词显示时当前歌词颜色变换
      this.handleLyricShow(newVal)
      this.time = parseInt(newVal)
    },
    time() {
      let nowLyc = document.getElementsByClassName('finishLycItem')
      let scrH = 0
      for (let i = 5; i < nowLyc.length; i++) {
        scrH += nowLyc[i].offsetHeight
      }
      jquery('#lyc').animate({ scrollTop: scrH })
      //当用户正在拖动进度条时，进度条不自动变化
      if (
        !$('#processId')
          .find('.range-knob-wrap')
          .hasClass('range-knob-active-state')
      ) {
        this.moveValue = (this.currentTime / this.duration).toFixed(4) * 100
      }
    },
  },
  computed: {
    ...mapGetters({
      currentTime: 'currentTime',
      duration: 'duration',
      getLyricsArr: 'getLyricsArr',
      playBtnClass: 'playBtnClass',
      nowSong: 'nowSong',
      getMusicPlace: 'getMusicPlace',
      getUserInfo: 'getUserInfo',
      getThemeDark: 'getThemeDark',
      getVolume: 'getVolume',
      getSingerPoster: 'getSingerPoster',
      getManageState: 'getManageState',
      getPageGradation:'getPageGradation',
    }),
  },
  data() {
    return {
      moveValue: 0, //进度条进度值
      time: 0,
      lycShow: true,
      oldProcess: -1, //手动调整进度条时，歌词进度改变要用到此值。
    }
  },

  methods: {
    ...mapActions({
      play: 'play',
      setCurrentTime: 'setCurrentTime',
      openListState: 'openListState',
      prevMusic: 'prevMusic',
      nextMusic: 'nextMusic',
      setLyrics: 'setLyrics',
      // setLyricsArr:'setLyricsArr',
      setNowSong: 'setNowSong',
      sendVolume: 'sendVolume',
      sendSingerPoster: 'sendSingerPoster',
      changePageGradation:'changePageGradation',
    }),
    //进入页面后
    pageAfterin(){
      switch (this.from){
        case 'home':
          this.changePageGradation(1);
          break;
        case 'search':
          this.changePageGradation(2);
          break;
      }
    },
    //去上传歌词
    goToUpdateLyc(e) {
      console.log('goToUpdateLyc', e)
      this.$f7router.navigate('/upload/', {
        props: {
          isUpdate: true,
          songInfo: e,
        },
      })
    },
    //去分享歌曲
    goToShare(){
      let self = this;
      this.$f7router.navigate('/toShare/', {
        props: {
          shareType: 'song',
          share: self.nowSong,
        },
      })
    },
    showOrhiddenLyc() {
      this.lycShow = !this.lycShow
    },
    //cTime:当前歌曲播放时间
    handleLyricShow(cTime) {
      let lyricContainer = document.getElementById('lyc')
      let lyricsResult = this.getLyricsArr
      //遍历所有歌词，看哪句歌词的时间与当然时间吻合
      for (var i = 0, l = lyricsResult.length; i < l; i++) {
        let lycItem = lyricContainer.getElementsByClassName('lycItem')[i]
        if (
          (i < l - 1 &&
            cTime /*当前播放的时间*/ > lyricsResult[i][0] &&
            cTime < lyricsResult[i + 1][0]) ||
          (i === l - 1 && cTime /*当前播放的时间*/ > lyricsResult[i][0])
        ) {
          //显示到页面
          lycItem.className = 'lycItem finishLycItem currentLycItem'
        } else if (cTime > lyricsResult[i][0]) {
          lycItem.className = 'lycItem finishLycItem'
        } else {
          lycItem.className = 'lycItem'
        }
      }
    },
    onPriceChange(value) {
      console.log(value, this.oldProcess, 'onPriceChange')
      let distance = Math.ceil(100 / this.duration)
      if (this.oldProcess === -1) {
        this.oldProcess = value
      } else {
        if (
          value > this.oldProcess + distance ||
          value < this.oldProcess - distance
        ) {
          if (this.duration > 0 && value >= 0) {
            setTimeout(() => {
              this.setCurrentTime((value * this.duration) / 100)
            }, 0)
          }
        }
        this.oldProcess = value
      }
    },

    onVolumeChange(value) {
      // this.sendVolume(value);
      this.$store.dispatch('sendVolume', value)
    },
    changeFav(nowSongInfo) {
      let qData = {
        songId: nowSongInfo.songId,
        userId: this.getUserInfo.userid,
      }
      if (nowSongInfo.isFavorite) {
        delFromMyFavorite(qData)
          .then((res) => {
            if (res.code === 200) {
              nowSongInfo.isFavorite = false
              this.setNowSong(nowSongInfo)
              this.$f7ready((f7) => {
                let toastTop = f7.toast.create({
                  text: '取消成功',
                  position: 'top',
                  closeTimeout: 1500,
                })
                toastTop.open()
              })
            }
          })
          .catch((err) => {
            console.log(err)
          })
      } else {
        addToMyFavorite(qData)
          .then((res) => {
            if (res.code === 200) {
              nowSongInfo.isFavorite = true
              this.setNowSong(nowSongInfo)
              this.$f7ready((f7) => {
                let toastTop = f7.toast.create({
                  text: '添加成功',
                  position: 'top',
                  closeTimeout: 1500,
                })
                toastTop.open()
              })
            }
          })
          .catch((err) => {
            console.log(err)
          })
      }
    },
  },
  mounted() {
    //歌手海报背景图
    let loading_flag = true
    let img_tim = new Image()
    img_tim.src = '/static/playerInfo_loading.png'
    img_tim.onload = () => {
      if (loading_flag) {
        this.$refs.bg.style.backgroundImage = `url('${img_tim.src}')`
      }
    }
    if (this.nowSong.singer) {
      getSingerPosterUrl({ name: this.nowSong.singer })
        .then((res) => {
          if (res.code === 200) {
            this.sendSingerPoster({
              singer: this.nowSong.singer,
              url: res.data.posterUrl,
            })
          } else {
            let timUrl
            if (this.getThemeDark) {
              timUrl = '/static/playerInfo_bg6.jpg'
            } else {
              timUrl = '/static/playerInfo_bg2.jpg'
            }
            this.sendSingerPoster({
              singer: '',
              url: timUrl,
            })
          }
          let imgg = new Image()
          imgg.src = this.getSingerPoster.url
          imgg.onload = () => {
            loading_flag = false
            this.$refs.bg.style.backgroundImage = `url('${imgg.src}')`
          }
        })
        .catch((err) => {
          console.log(err)
        })
    } else {
      let timUrl
      if (this.getThemeDark) {
        timUrl = '/static/playerInfo_bg6.jpg'
      } else {
        timUrl = '/static/playerInfo_bg2.jpg'
      }
      let imgg = new Image()
      imgg.src = timUrl
      imgg.onload = () => {
        loading_flag = false
        this.$refs.bg.style.backgroundImage = `url('${imgg.src}')`
      }
    }
    setTimeout(() => {
      this.$store.dispatch('setLyrics', this.nowSong)
      // this.setLyricsArr();
    }, 50)
    setTimeout(function() {
      let nowLyc = document.getElementsByClassName('finishLycItem')
      let scrH = 0
      for (let i = 0; i < nowLyc.length; i++) {
        scrH += nowLyc[i].offsetHeight
      }
      jquery('#lyc').scrollTop(scrH)
    }, 100)
    //监听歌曲信息修改
    let self = this
    this.$bus
      .$off('updateSongInfoAfterUpdate')
      .$on('updateSongInfoAfterUpdate', (newSongInfo) => {
        for (let key in newSongInfo) {
          self.nowSong[key] = newSongInfo[key]
        }
        // self.$store.dispatch('setNowSong', timNowSong)
        self.setNowSong(self.nowSong)
      })
  },
}
</script>
<style lang="scss" scoped>
.dark_bg {
  background: url('../assets/img/playerInfo_loading.png');
}
.light_bg {
  background: url('../assets/img/playerInfo_loading.png');
}
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s;
}
.fade-enter,
.fade-leave-active {
  opacity: 0;
}
.bg_blur {
  float: left;
  width: 100%;
  height: 100vh;
  background-repeat: no-repeat;
  background-position: center;
  background-size: cover;
  -webkit-filter: blur(2px);
  -moz-filter: blur(2px);
  -o-filter: blur(2px);
  -ms-filter: blur(2px);
  // filter: blur(2px);
  filter: brightness(75%);
  // opacity: 0.9;
}
.navbarInfo {
  display: flex;
  align-items: center;
  height: 9vh;
  .navbar_l {
    width: 12vw;
    .svg-icon {
      width: 0.4rem;
      height: 0.4rem;
    }
  }
  .navbar_m {
    flex: 1;
    max-width: 76vw;
    margin-left: 1vw;
    display: flex;
    align-items: flex-end;
    flex-grow: 0;
    span {
      font-size: 20px;
      white-space: nowrap;
      color: #ffffff;
    }
    .mText {
      max-width: 72vw;
      overflow: hidden;
      flex-shrink: 1;
      flex-flow: 1;
      .scrollSong {
      }
    }
    .mText2 {
      .scrollSinger {
        font-size: 16px;
        color: #f0f0f0;
        margin-left: 0.1rem;
      }
    }
  }
}
.light .lyc_box {
  .lycItem {
    color: #ffffff;
  }
  .currentLycItem {
    color: #d82c0a;
  }
}
.dark .lyc_box {
  .lycItem {
    color: #ffffff;
  }
  .currentLycItem {
    color: #d82c0a;
  }
}
.volume_box {
  height: 7vh;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  margin-left: 4vw;
  .svg-icon {
    height: 0.25rem;
    width: 0.25rem;
    margin-right: 4vw;
  }
  .range-slider.range-slider-horizontal {
    width: 75vw;
  }
}
.lyc_box {
  height: 62vh;
  ul {
    height: 60vh;
    margin: 0vh 0;
    overflow-y: scroll;
    padding: 0;
    transition: all 2s;
    scroll-behavior: smooth;
  }
  .lycItem {
    // transition: all 1.0s;
    transition: all 0.7s;
    margin: 0 auto;
    padding: 0.05rem;
    text-align: center;
    color: #f0f0f0;
    font-size: 16px;
  }
  .currentLycItem {
    color: #d82c0a;
    // color:#000000;
    font-size: 19px;
    font-weight: 600;
  }
}
.button_bar {
  height: 4vh;
  display: flex;
  align-items: center;
  width: 92vw;
  justify-content: space-between;
  margin: 0 4vw;
  .button_bar_left {
    display: flex;
    align-items: center;
    justify-content: flex-start;
  }
  .button_bar_right {
    display: flex;
    align-items: center;
    justify-content: flex-start;
  }
  .button {
    height: 5vh;
    display: flex;

    .svg-icon {
      width: 5vh;
      height: 5vh;
    }
  }
}
.progress_box {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 6vh;
  margin-top: 1vh;
  .progress {
    width: 70%;
    // height:.5vh;
  }
}
.playBtn_box {
  height: 10vh;
  display: flex;
  justify-content: space-around;
  align-items: center;
  .button {
    flex: 1;
    width: 0.5rem;
    height: 0.5rem;
    display: flex;
    align-items: center;
  }
  .playSvg {
    width: 0.5rem;
    height: 0.5rem;
  }
  .nextSvg,
  .lastSvg {
    width: 0.3rem;
    height: 0.3rem;
  }
  .songList {
    flex: 1;
  }
  .listSvg {
    width: 0.3rem;
    height: 0.3rem;
  }
}
</style>
